package com.example.yichuangyun.ui.activity.mine;

import android.os.Bundle;

import com.example.yichuangyun.application.MyApplication;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityQrResultBinding;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.QrModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.utils.ToastHelper;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 扫码结果
 */
public class QrResultActivity extends BaseActivity<ActivityQrResultBinding, BaseViewModel> {

    private String id;
    private String requestNo;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            id = bundle.getString(Constant.idKey);
            requestNo = bundle.getString(Constant.requestNoKey);
        }
    }

    @Override
    protected void initClick() {
        binding.tvClose.setOnClickListener(v -> finish());
        binding.tvCancel.setOnClickListener(v -> finish());
        binding.tvConfirm.setOnClickListener(v -> scanLogin());
    }

    /**
     * 扫码登录
     */
    private void scanLogin() {
        showLoadingDialog();
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("id", id);
            requestDate.put("requestNo", requestNo);
            requestDate.put("phone", MyApplication.manager.getPhone());
            requestDate.put("jobNumber", MyApplication.manager.getJobNumber());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().scanLogin(requestBody), new MyObserver<QrModel>() {
            @Override
            protected void onSuccess(QrModel qrModel) {
                if (qrModel.getStatus() == 1) {
                    finish();
                } else {
                    ToastHelper.show(qrModel.getMessage());
                }
                dismissLoadingDialog();
            }
        });
    }
}